﻿using System.Net.Http;
using System.Text;
using System.Windows;
using Newtonsoft.Json;
using Serilog;
using System.IO;

namespace PC
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly HttpClient _httpClient;
        private const string BaseUrl = "http://localhost:3003"; // 修改为正确的API路径
        private readonly ILogger _logger;
        private const string UserDataFile = "userdata.json";

        public MainWindow()
        {
            InitializeComponent();
            _httpClient = new HttpClient();
            _logger = Log.Logger;
            _logger.Debug("初始化完成，服务器地址: {BaseUrl}", BaseUrl);
            
            // 尝试自动登录
            AutoLoginAsync();
            
            _logger.Debug("等待用户操作");
        }

        private async void AutoLoginAsync()
        {
            try
            {
                if (File.Exists(UserDataFile))
                {
                    var json = File.ReadAllText(UserDataFile);
                    var savedData = JsonConvert.DeserializeObject<SavedUserData>(json);
                    if (savedData != null)
                    {
                        _logger.Debug("找到保存的用户信息，尝试自动登录");
                        
                        var loginData = new { username = savedData.Username, password = savedData.Password };
                        var content = new StringContent(
                            JsonConvert.SerializeObject(loginData),
                            Encoding.UTF8,
                            "application/json");

                        var loginUrl = $"{BaseUrl}/auth/login";
                        _logger.Debug("发送登录请求到: {Url}", loginUrl);
                        
                        var response = await _httpClient.PostAsync(loginUrl, content);
                        var responseContent = await response.Content.ReadAsStringAsync();
                        
                        if (response.IsSuccessStatusCode)
                        {
                            var result = JsonConvert.DeserializeObject<LoginResponse>(responseContent);
                            _logger.Debug("自动登录响应解析结果: {@LoginResponse}", result);
                            if (result?.Success == true && result.User != null)
                            {
                                _logger.Information("自动登录成功");
                                _logger.Debug("用户信息: {@UserInfo}", result.User);
                                var chatWindow = new ChatWindow(new ChatWindow.UserInfo
                                {
                                    Username = result.User.Username,
                                    Status = "online",
                                    UserId = result.User.UserId
                                });
                                chatWindow.Show();
                                this.Close();
                            }
                            else
                            {
                                _logger.Warning("自动登录失败：无效的响应数据");
                                LoadSavedUserInfo();
                            }
                        }
                        else
                        {
                            _logger.Warning("自动登录失败，显示登录界面");
                            LoadSavedUserInfo(); // 仍然填充用户名和密码
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "自动登录失败");
                LoadSavedUserInfo(); // 仍然填充用户名和密码
            }
        }

        private void LoadSavedUserInfo()
        {
            try
            {
                if (File.Exists(UserDataFile))
                {
                    var json = File.ReadAllText(UserDataFile);
                    var savedData = JsonConvert.DeserializeObject<SavedUserData>(json);
                    if (savedData != null)
                    {
                        _logger.Debug("找到保存的用户信息");
                        UsernameTextBox.Text = savedData.Username;
                        PasswordBox.Password = savedData.Password;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "加载保存的用户信息失败");
            }
        }

        private void SaveUserInfo(string username, string password)
        {
            try
            {
                var userData = new SavedUserData
                {
                    Username = username,
                    Password = password
                };
                var json = JsonConvert.SerializeObject(userData);
                File.WriteAllText(UserDataFile, json);
                _logger.Debug("用户信息已保存");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "保存用户信息失败");
            }
        }

        private void ApiTestButton_Click(object sender, RoutedEventArgs e)
        {
            _logger.Debug("打开API测试工具");
            var apiTestWindow = new ApiTestWindow();
            apiTestWindow.Show();
        }

        private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            _logger.Debug("用户点击注册按钮");
            var registerWindow = new RegisterWindow();
            _logger.Debug("打开注册窗口");
            var result = registerWindow.ShowDialog();
            
            if (result == true)
            {
                _logger.Debug("注册成功，自动填充用户名: {Username}", registerWindow.UsernameTextBox.Text);
                UsernameTextBox.Text = registerWindow.UsernameTextBox.Text;
                PasswordBox.Focus();
            }
            else
            {
                _logger.Debug("用户取消注册或注册失败");
            }
        }

        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LoginButton.IsEnabled = false;
                ErrorMessageText.Text = string.Empty;

                var username = UsernameTextBox.Text;
                var password = PasswordBox.Password;

                _logger.Debug("收到登录请求，用户名: {Username}", username);

                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    _logger.Warning("登录验证失败：用户名或密码为空");
                    ErrorMessageText.Text = "用户名和密码不能为空";
                    return;
                }

                _logger.Information("正在尝试登录用户: {Username}", username);
                _logger.Debug("准备登录数据");

                var loginData = new { username, password };
                var content = new StringContent(
                    JsonConvert.SerializeObject(loginData),
                    Encoding.UTF8,
                    "application/json");

                var loginUrl = $"{BaseUrl}/auth/login";
                _logger.Debug("发送登录请求到: {Url}", loginUrl);
                _logger.Debug("请求内容: {Content}", JsonConvert.SerializeObject(loginData));
                
                var response = await _httpClient.PostAsync(loginUrl, content);
                var responseContent = await response.Content.ReadAsStringAsync();
                
                _logger.Debug("服务器响应状态码: {StatusCode}", response.StatusCode);
                _logger.Debug("服务器响应内容: {Content}", responseContent);

                if (response.IsSuccessStatusCode)
                {
                    var result = JsonConvert.DeserializeObject<LoginResponse>(responseContent);
                    _logger.Debug("登录响应解析结果: {@LoginResponse}", result);
                    if (result?.Success == true && result.User != null)
                    {
                        _logger.Information("登录成功");
                        _logger.Debug("用户信息: {@UserInfo}", result.User);
                        var chatWindow = new ChatWindow(new ChatWindow.UserInfo
                        {
                            Username = result.User.Username,
                            Status = "online",
                            UserId = result.User.UserId
                        });
                        chatWindow.Show();
                        this.Close();
                    }
                    else
                    {
                        _logger.Error("登录失败：服务器返回失败状态");
                        ErrorMessageText.Text = "登录失败：用户名或密码错误";
                    }
                }
                else
                {
                    _logger.Error("登录失败：HTTP状态码 {StatusCode}", response.StatusCode);
                    if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        ErrorMessageText.Text = "登录失败：用户不存在，请先注册";
                    }
                    else
                    {
                        ErrorMessageText.Text = $"登录失败：{response.StatusCode}";
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                _logger.Error(ex, "网络请求错误");
                _logger.Debug("异常详情: {ExceptionDetails}", ex.ToString());
                ErrorMessageText.Text = "网络连接失败，请检查服务器是否启动";
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "登录过程中发生未知错误");
                _logger.Debug("异常详情: {ExceptionDetails}", ex.ToString());
                ErrorMessageText.Text = $"发生错误：{ex.Message}";
            }
            finally
            {
                LoginButton.IsEnabled = true;
                _logger.Debug("登录按钮已重新启用");
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            _logger.Information("=== 聊天客户端关闭 ===");
            Log.CloseAndFlush();
        }
    }

    public class SavedUserData
    {
        public string Username { get; set; } = null!;
        public string Password { get; set; } = null!;
    }

    public class LoginResponse
    {
        public bool Success { get; set; }
        public UserInfo User { get; set; } = null!;
    }

    public class UserInfo
    {
        public string Username { get; set; } = null!;
        public string Status { get; set; } = null!;
        public string UserId { get; set; } = null!;
    }
}